package com.bdmc.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdmc.base.domain.BaseCar;
import com.bdmc.base.domain.BaseDevice;
import com.bdmc.base.domain.bo.BaseCarBo;
import com.bdmc.base.domain.vo.BaseCarVo;
import com.bdmc.base.mapper.BaseCarMapper;
import com.bdmc.base.service.IBaseCarService;
import com.bdmc.base.service.IBaseDeviceService;
import com.bdmc.common.core.domain.PageQuery;
import com.bdmc.common.core.mybatisplus.core.ServicePlusImpl;
import com.bdmc.common.core.page.TableDataInfo;
import com.bdmc.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 车辆信息Service业务层处理
 *
 * @author bdmc
 * @date 2022-03-03
 */
@Service
public class BaseCarServiceImpl extends ServicePlusImpl<BaseCarMapper, BaseCar, BaseCarVo> implements IBaseCarService {
    @Autowired
    IBaseDeviceService deviceService;

    @Override
    public BaseCarVo queryById(Long carId) {
        return getVoById(carId);
    }

    @Override
    public TableDataInfo<BaseCarVo> queryPageList(BaseCarBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BaseCar> lqw = buildQueryWrapper(bo);
        Page<BaseCarVo> result = pageVo(pageQuery.build(), lqw);

        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<BaseCarVo> mySelectPage(BaseCarBo bo, PageQuery pageQuery) {
        return TableDataInfo.build(baseMapper.mySelectPage(pageQuery.build(), bo));
    }

    @Override
    public List<BaseCarVo> queryList(BaseCarBo bo) {
        return baseMapper.mySelectPage(bo);
    }

    @Override
    public List<BaseCarVo> queryAllForXXLJob(BaseCarBo bo) {
        return baseMapper.queryAllForXXLJob(bo);
    }

    private LambdaQueryWrapper<BaseCar> buildQueryWrapper(BaseCarBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseCar> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDeptId() != null, BaseCar::getDeptId, bo.getDeptId());
        lqw.eq(StringUtils.isNotBlank(bo.getCarNum()), BaseCar::getCarNum, bo.getCarNum());
        lqw.eq(StringUtils.isNotBlank(bo.getCarType()), BaseCar::getCarType, bo.getCarType());
        lqw.eq(bo.getBuyDate() != null, BaseCar::getBuyDate, bo.getBuyDate());
        lqw.eq(bo.getMileage() != null, BaseCar::getMileage, bo.getMileage());
        return lqw;
    }

    @Override
    public Boolean insertByBo(BaseCarBo bo) {
        BaseCar add = BeanUtil.toBean(bo, BaseCar.class);
        validEntityBeforeSave(add);
        boolean flag = save(add);
        if (flag) {
            bo.setCarId(add.getCarId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(BaseCarBo bo) {
        BaseCar update = BeanUtil.toBean(bo, BaseCar.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(BaseCar entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    @Override
    public Boolean bindDevice(BaseCarBo bo) {
        synchronized (this) {
            BaseCar car = getById(bo.getCarId());
            Assert.notNull(car, "未找到该车辆信息。");
            if (bo.getDeviceId() != null) {
                BaseDevice device = deviceService.getById(bo.getDeviceId());
                Assert.notNull(device, "设备不存在，请检查设备信息。");
                long count = count(new LambdaQueryWrapper<BaseCar>().eq(BaseCar::getDeviceId, bo.getDeviceId()));
                Assert.isTrue(count == 0, "设备已被绑定，请选择其他设备");
                car.setDeviceId(bo.getDeviceId());
                device.setBind(1);
                device.setBindTarget(car.getCarNum());
                deviceService.updateById(device);
                updateById(car);
            }
            if (bo.getOilDeviceId() != null) {
                BaseDevice device = deviceService.getById(bo.getOilDeviceId());
                long count = count(new LambdaQueryWrapper<BaseCar>().eq(BaseCar::getOilDeviceId, bo.getOilDeviceId()));
                Assert.isTrue(count == 0, "设备已被绑定，请选择其他设备");
                car.setOilDeviceId(bo.getOilDeviceId());
                device.setBind(1);
                device.setBindTarget(car.getCarNum());
                deviceService.updateById(device);
                updateById(car);
            }
        }
        return true;
    }

    @Override
    public Boolean unbindDevice(BaseCarBo bo) {
        synchronized (this) {
            BaseCar car = getById(bo.getCarId());
            Assert.notNull(car, "未找到该车辆信息");
            if (bo.getDeviceId() != null && bo.getDeviceId() > 0 && car.getDeviceId().equals(bo.getDeviceId())) {
                car.setDeviceId(0L);
                updateById(car);
                BaseDevice device = deviceService.getById(bo.getDeviceId());
                device.setBind(0);
                device.setBindTarget("");
                deviceService.updateById(device);
            }
            if (bo.getOilDeviceId() != null && bo.getOilDeviceId() > 0 && car.getOilDeviceId().equals(bo.getOilDeviceId())) {
                car.setOilDeviceId(0L);
                updateById(car);
                BaseDevice device = deviceService.getById(bo.getOilDeviceId());
                device.setBind(0);
                device.setBindTarget("");
                deviceService.updateById(device);
            }
            return true;
        }
    }
}
